package tsou.com.simple.realmtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import io.realm.OrderedCollectionChangeSet;
import io.realm.OrderedRealmCollectionChangeListener;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import tsou.com.simple.realmtest.adapter.MyAdapter;
import tsou.com.simple.realmtest.bean.Men;
import tsou.com.simple.realmtest.bean.Person;
import tsou.com.simple.realmtest.utils.UIUtils;

public class QueryActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView mListview;
    private List<String> titles = new ArrayList<>();
    private Realm mRealm;
    private RealmResults<Men> menList2;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (menList2 != null) {
            menList2.removeChangeListener(callback);
            menList2.removeAllChangeListeners();
        }
        if (mRealm != null && !mRealm.isClosed()) {
            mRealm.close();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mRealm = UIUtils.getRealmInstance();
        initData();
        initView();
        initListener();
    }

    private void initData() {
        titles.add("同步操作：findAll查询");
        titles.add("异步操作：findAllAsync查询(isLoaded)");
        titles.add("异步操作：findAllAsync查询(RealmChangeListener)");
        titles.add("findFirst :查询第一条数据");
        titles.add("equalTo :根据条件单级查询");
        titles.add("equalTo :根据条件多级查询");
        titles.add("聚合");
        titles.add("or的使用");
        titles.add("排序");
        titles.add("区间查询");
    }

    private void initView() {
        mListview = (ListView) findViewById(R.id.listview);

        mListview.setAdapter(new MyAdapter(this, titles));
    }

    private void initListener() {
        mListview.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            default:
                break;
            case 0://同步操作：findAll查询
                /**
                 * 注意：RealmResults虽然实现了List接口，不过有很多方法是不能用的。
                 * 比如add、addAll、remove、clear等，
                 * 调用后会直接抛异常。
                 * 因为它们都被标记为@Deprecated了。
                 */
                RealmResults<Men> menList = mRealm.where(Men.class)
                        .findAll();
                for (int i = 0; i < menList.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            menList.get(i).getName() + "----" + menList.get(i).getAge());
                }

                break;
            case 1://异步操作：findAllAsync查询(isLoaded)
                RealmResults<Men> menList1 = mRealm.where(Men.class)
                        .findAllAsync();
                menList1.load();//等到查询完成。这将阻塞该线程，使查询再次同步
                if (menList1 != null && menList1.isLoaded()) {
                    for (int i = 0; i < menList1.size(); i++) {
                        Log.d("huangxiaoguo", "huangixoaguo==>" +
                                menList1.get(i).getName() + "----" + menList1.get(i).getAge());
                    }
                }
                break;
            case 2://异步操作：findAllAsync查询(RealmChangeListener)
                menList2 = mRealm.where(Men.class)
                        .findAllAsync();
                menList2.addChangeListener(callback);
                break;
            case 3://findFirst :查询第一条数据
                Men men = mRealm.where(Men.class).findFirst();
                Log.d("huangxiaoguo", "huangixoaguo==>" +
                        men.getName() + "----" + men.getAge());
                break;
            case 4://equalTo ——根据条件单级查询
                RealmResults<Men> menRealmResults = mRealm.where(Men.class)
                        .equalTo("name", "huangxiaoguo1").findAll();
                for (int i = 0; i < menRealmResults.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            menRealmResults.get(i).getName() + "----" + menRealmResults.get(i).getAge());
                }
                break;
            case 5://equalTo ——根据条件多级查询
                //只能是一对一的表，一对多时，子表查询条件无效
                RealmResults<Person> people = mRealm.where(Person.class)
                        .equalTo("city", "杭州")
                        .equalTo("men.age", 20)//这是他的子类Men的属性
                        .findAll();
                for (int i = 0; i < people.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            people.get(i).getMen().getName() + "----" +
                            people.get(i).getMen().getAge());
                }
                break;
            case 6://聚合
                /**
                 * sum()：对指定字段求和。
                 average()：对指定字段求平均值。
                 min(): 对指定字段求最小值。
                 max() : 对指定字段求最大值。count : 求结果集的记录数量。
                 findAll(): 返回结果集所有字段，返回值为RealmResults队列
                 findAllSorted() : 排序返回结果集所有字段，返回值为RealmResults队列
                 between(), greaterThan(),lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
                 equalTo() & notEqualTo()
                 contains(), beginsWith() & endsWith()
                 isNull() & isNotNull()
                 isEmpty()& isNotEmpty()
                 */
                RealmResults<Men> results = mRealm.where(Men.class).findAll();
                long sum = results.sum("age").longValue();
                long min = results.min("age").longValue();
                long max = results.max("age").longValue();
                double average = results.average("age");
                long matches = results.size();
                Log.d("huangxiaoguo", "sum=" + sum + ",min=" + min + ",max=" + max +
                        ",average=" + average + ",matches=" + matches);
                break;
            case 7://or的使用
                RealmResults<Men> menList2 = mRealm.where(Men.class)
                        .equalTo("name", "huangxiaoguo0")
                        .or().equalTo("name", "huangxiaoguo2")
                        .findAll();
                for (int i = 0; i < menList2.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList2.get(i).getName() +
                            ",age=" + menList2.get(i).getAge());
                }
                break;
            case 8://排序
                RealmResults<Men> menList3 = mRealm.where(Men.class).findAll();
                menList3 = menList3.sort("age"); //根据age，正序排列
                for (int i = 0; i < menList3.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList3.get(i).getName() +
                            ",age=" + menList3.get(i).getAge());
                }
                menList3 = menList3.sort("age", Sort.DESCENDING);//逆序排列
                for (int i = 0; i < menList3.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList3.get(i).getName() +
                            ",age=" + menList3.get(i).getAge());
                }

                break;
            case 9:
                RealmResults<Men> menList4 = mRealm.where(Men.class)
                        .between("age", 0, 30)
                        .findAll();
                for (int i = 0; i < menList4.size(); i++) {
                    Log.d("huangxiaoguo", "name=" + menList4.get(i).getName() +
                            ",age=" + menList4.get(i).getAge());
                }
                break;

        }
    }

    /**
     * 异步操作的监听
     */
    private OrderedRealmCollectionChangeListener<RealmResults<Men>> callback = new OrderedRealmCollectionChangeListener<RealmResults<Men>>() {
        @Override
        public void onChange(RealmResults<Men> collection, OrderedCollectionChangeSet changeSet) {
            if (changeSet == null) {
                //第一次异步返回一个空的变更集。
                for (int i = 0; i < collection.size(); i++) {
                    Log.d("huangxiaoguo", "huangixoaguo==>" +
                            collection.get(i).getName() + "----" + collection.get(i).getAge());
                }
            } else {
                //每次RealmResults被更新时都会被调用
            }
        }
    };
}
